<template>
  <div v-loading="listLoading" class="createPost-container">

    <el-form ref="postForm" :model="postForm" label-width="80px">

      <div class="createPost-main-container" style="width:600px;">
        <el-form-item v-if="isEdit" label="设备编号">
          <el-input v-model="postForm.id" disabled></el-input>
        </el-form-item>

        <el-form-item label="设备组名">
          <el-select v-model="postForm.U_MEQG" @change="changeOper($event)" default-first-option placeholder="请选择设备组" :disabled="isEdit">
<!--            <el-option label="混胶" value="HJ"></el-option>
            <el-option label="涂布" value="TB"></el-option>
            <el-option label="熟化" value="SH"></el-option>
            <el-option label="分切" value="FQ"></el-option> -->
            <el-option v-for="item in opers" :key="item.Code" :label="item.Name" :value="item.Code"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备编号">
          <el-input v-model="postForm.Code" placeholder="请输入设备编号" :disabled="isEdit"></el-input>
        </el-form-item>

        <el-form-item label="设备名称">
          <el-input v-model="postForm.Name" placeholder="请输入设备设备名称" ></el-input>
        </el-form-item>

        <el-form-item v-if="false" label="设备状态">
          <el-radio-group v-model="postForm.Canceled" >
            <el-radio label="N" @input.native="onChangeisUsed('N')">启用</el-radio>
            <el-radio label="Y" @input.native="onChangeisUsed('Y')">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="backtoPreviousTags(false)">取消</el-button>
        </el-form-item>
      </div>
    </el-form>

  </div>
</template>

<script>
import axios from 'axios'
import { fetchOpers, fetchList, updateMEQUs } from '@/api/res'

const defaultForm = {
  status: 'draft',
  MEQG_Name: '',
  U_MEQG:'',
  Code: '',
  Name: '',
  U_VisOrder: '',
  Canceled: '',
  id: undefined,
  isUsed: false
}

export default {
  name: 'ResDetail',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      console.log('-------validateRequire-----------',rule,value)
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      listLoading: true,
      rules: {
        title: [{ validator: validateRequire }],
        startDate: [{ validator: validateRequire }],
        cost: [{ validator: validateRequire }],
        description: [{ validator: validateRequire }],
        //showBillUrl: [{ validator: validateRequire }]
      },
      tempRoute: {},
      isUsed: 1,
      opers:[]
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }else{
      this.postForm.Canceled = 'N'
      this.postForm.U_MEQG = 'HJ'

      this.setTagsViewTitle()
      this.setPageTitle()

      this.listLoading = false
    }
    this.getOpers()
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    onSubmit(){
      console.log('Submit',JSON.stringify(this.postForm))
    },
    onChangeisUsed(val){
      this.postForm.Canceled = val
      console.log('onChangeisUsed---------',this.postForm.Canceled)
    },
    changeOper(val){
      this.postForm.U_MEQG = val
      console.log('changeOper--------',val,this.postForm)
    },
    getOpers(){
      fetchOpers().then(res=>{
        this.opers = res
      }).catch(err=> {
        console.log('error submit!!',err);
      });
    },

    backtoPreviousTags(reflush){
      const title = '设备清单'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/delView', route).then(({ visitedViews }) => {
        const latestView = visitedViews.slice(-1)[0]
        console.log('latestView--------------',latestView)
        if (latestView) {
          this.$router.push(latestView.fullPath)
          if(reflush && reflush == true){
            this.$router.go(0)
          }
        } else {
          if (view.name === 'Dashboard') {
            this.$router.replace({ path: '/redirect' + view.fullPath })
          } else {
            this.$router.push('/')
          }
        }
      })
    },

    fetchDataTest(id){
      const list = [
        {id:1,MEQG_Code:'HJ',MEQG_Name:'混胶',Code:'A-1',Name:'A-1',U_VisOrder:'A1',Canceled:'N'},
        {id:2,MEQG_Code:'HJ',MEQG_Name:'混胶',Code:'A-2',Name:'A-2',U_VisOrder:'A2',Canceled:'N'},
        {id:3,MEQG_Code:'HJ',MEQG_Name:'混胶',Code:'A-3',Name:'A-3',U_VisOrder:'A3',Canceled:'N'},
        {id:4,MEQG_Code:'HJ',MEQG_Name:'混胶',Code:'A-4',Name:'A-4',U_VisOrder:'A4',Canceled:'N'},
        {id:5,MEQG_Code:'HJ',MEQG_Name:'混胶',Code:'B-1',Name:'B-1',U_VisOrder:'A5',Canceled:'N'},
        {id:6,MEQG_Code:'HJ',MEQG_Name:'混胶',Code:'B-2',Name:'B-2',U_VisOrder:'A6',Canceled:'N'},
        {id:7,MEQG_Code:'HJ',MEQG_Name:'混胶',Code:'B-3',Name:'B-3',U_VisOrder:'A7',Canceled:'N'},
        {id:8,MEQG_Code:'HJ',MEQG_Name:'混胶',Code:'B-4',Name:'B-4',U_VisOrder:'A8',Canceled:'N'}
      ]

      var item = list.filter(item => item.id == id )
      this.postForm = JSON.parse(JSON.stringify(item))[0];
      this.postForm.isUsed = this.postForm.Canceled == ''
      this.isUsed = this.postForm.Canceled == '' ? 1 : 0

      // set tagsview title
      this.setTagsViewTitle()

      // set page title
      this.setPageTitle()
    },

    fetchData(id) {
      this.listLoading = true
      fetchList({ page:1,limit:2000}).then(resData=>{
        const {flist} = resData
        var _list = flist.map(item=>{
          item.id = item.DocEntry
          return item
        })

        if(this.isEdit){
          _list = _list.filter(v => v.DocEntry == id )
        }

        this.postForm = JSON.parse(JSON.stringify(_list))[0];
        this.postForm.isUsed = this.postForm.Canceled == ''
        this.isUsed = this.postForm.Canceled == '' ? 1 : 0

        // set tagsview title
        this.setTagsViewTitle()

        // set page title
        this.setPageTitle()

        this.listLoading = false
      }).catch(err=> {
        console.log('error submit!!',err);
        this.listLoading = false
      });

    },

    setTagsViewTitle() {
      const title = '设备编辑'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },

    setPageTitle() {
      const title = '设备编辑'
      document.title = `${title} - ${this.postForm.id}`
    },

    submitForm() {
      console.log('Submit',JSON.stringify(this.postForm))
      //{"row_number":"8","DocEntry":"20","Code":"S1","Name":"S1","Canceled":"N","U_MLOT":"running","U_MEQG":"FQ","U_VisOrder":"A1","U_LastMPCP":"99","id":"20","MEQG_Code":"FQ","MEQG_Name":"分切工程","scbh":"fqsc","zlbh":"fqzl","isUsed":false}
      if(this.postForm.U_MLOT == 'running'){
        this.$notify({ title: '提示', message: '设备状态运行中,不可变更!', type: 'warning', duration: 2000 })
        return
      }

      updateMEQUs(this.postForm).then(res=>{
        console.log('updateMEQUs---ok------', res)
        this.backtoPreviousTags(true)
        this.$notify({ title: '成功', message: '操作完成', type: 'success', duration: 2000 })
      }).catch(err=>{
        console.log('updateMEQUs---err------', err)
      })

    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

// .avatar{
//   width: 200px;
//   height: 200px;
//   border-radius: 50%;
// }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
